package org.will.demo.commands;

import org.reveno.atp.api.commands.CommandContext;
import org.reveno.atp.api.transaction.TransactionContext;
import org.will.cqrs.command.Command;
import org.will.cqrs.command.CommandAction;
import org.will.cqrs.command.ICommand;
import org.will.cqrs.command.ICommandAction;
import org.will.ddd.eventing.IDomainEvent;
import org.will.demo.domain.MQDemo;

/**
 * Created by EdifierWill on 2016/8/8.
 */
public class CreateMQDemoCommand extends Command<MQDemo>{

    public final Long _id;
    public final String _ename;
    public final Double _price;
    public final Double _inventory;

    public CreateMQDemoCommand(Long id,String ename,Double price,Double inventory){
        _id = id;
        _ename = ename;
        _price = price;
        _inventory = inventory;
        this.setDomainModelClass(MQDemo.class);
        this.needNewId(false);//是否获取新id(当无标识需要自行生成唯一标识时使用)
    }

    @Override
    public ICommandAction createAction(ICommand cmd) {
        return new CreateMQDemoCommandAction(cmd,cmd.getNewId());
    }

    public class CreateMQDemoCommandAction extends CommandAction {

        public CreateMQDemoCommandAction(ICommand cmd, long id) {
            super(cmd,id);
        }

        public void handler(ICommandAction action, TransactionContext ctx) {
            // TODO business logic here
            CreateMQDemoCommandAction a = (CreateMQDemoCommandAction)action;
            CreateMQDemoCommand command = ((CreateMQDemoCommand)a._cmd);
            //当需要使用新生成的标识使用 a._id 若使用cmd中的标识(或已经在其他处生成的使用command._id)
            MQDemo mqDemo = MQDemo.create(command._id, command._ename,command._price,command._inventory);
            //System.out.println("transactionAction(CreateMQDemoCommandAction):" + a._id);

            publishEvents(mqDemo,ctx);
            ctx.repo().store(command._id, mqDemo);
        }
    }
}
